package com.yyw.Service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yyw.bean.Criticism;
import com.yyw.bean.Tractate;
import com.yyw.bean.User;
import com.yyw.dao.CollectDao;
import com.yyw.dao.TractateDao;
import com.yyw.dao.UserDao;
import com.yyw.util.MyContext;
import com.yyw.util.Result;
import com.yyw.util.ResultFactory;

import cn.hutool.core.date.DateUtil;

@Service
public class TractateService {

    @Value("${my.session.user}")
    private String userAttr;

    @Autowired
    private TractateDao tractateDao;

    @Autowired
    private CollectDao collectDao;

    @Autowired
    private UserDao userDao;

    /**
     * 通过评论id为评论点赞
     *
     * @param id
     * @return
     */
    @Transactional
    public Result praiseCriticism(Long id) {
        if (id == null) {
            return ResultFactory.notice("评论id不合法");
        }
        Criticism criticism = tractateDao.getCriticismById(id);
        if (criticism == null) {
            return ResultFactory.notice("点赞失败");
        }

        Integer oknum = criticism.getOknum();
        criticism.setOknum(oknum + 1);
        int result = tractateDao.updateCriticismById(criticism);

        if (result > 0) {
            return ResultFactory.success("点赞成功");
        } else {
            return ResultFactory.failure("点赞失败");
        }
    }

    /**
     * 添加短文
     *
     * @param tractate
     * @return
     */
    @Transactional
    public Result saveTractate(Tractate tractate) {
        // 数据校验
        if (StringUtils.isEmpty(tractate.getTitle())) {
            return ResultFactory.notice("标题为空");
        }
        if (StringUtils.isEmpty(tractate.getFtitle())) {
            return ResultFactory.notice("副标题为空");
        }
        if (!tractate.checkLevel()) {
            return ResultFactory.notice("难度不合法");
        }
        if (StringUtils.isEmpty(tractate.getContent())) {
            return ResultFactory.notice("内容为空");
        }

        int num = tractateDao.saveTractate(tractate);
        if (num > 0) {
            return ResultFactory.success("添加成功");
        } else {
            return ResultFactory.failure("添加失败");
        }

    }

    /**
     * 分页查询短文，可以设置难度上限
     *
     * @param level
     * @param pageNo
     * @param pageNum
     * @return
     */
    public Result getTractates(Integer level, Integer pageNo, Integer pageNum) {
        // 数据校验
        if (level != null && (level < 0 || level > 5)) {
            return ResultFactory.notice("难度不合法");
        }
        if (pageNo == null || (pageNo < 1)) {
            return ResultFactory.notice("页数不合法");
        }
        if (pageNum == null || pageNum < 1) {
            return ResultFactory.notice("每页数量不合法");
        }

        if (level == null || level == 0) {
            level = 5;
        }

        PageHelper.startPage(pageNo, pageNum);
        List<Tractate> tractates = tractateDao.getTractates(level);
        PageInfo<Tractate> pageInfo = new PageInfo<>(tractates);
        return ResultFactory.success(pageInfo);
    }

    /**
     * 根据id获取短文
     *
     * @param id
     * @return
     */
    public Result getTractateById(Long id, Long userid) {
        if (id == null) {
            return ResultFactory.notice("数据不合法");
        }
        Tractate tractate = tractateDao.getTractateById(id);
        if (userid != null && tractate != null) {
            int i = collectDao.getCollectState(userid, id);
            if (i > 0) {
                tractate.setIsCollect(true);
            }
        }

        if (tractate != null) {
            User newUser = new User();
            User user = (User) MyContext.getHttpSession().getAttribute(userAttr);
            user.init();
            Date daydate = user.getDaydate();
            Integer daynum = user.getDaynum();
            Date monthdate = user.getMonthdate();
            Integer accumulatemonth = user.getAccumulatemonth();
            Integer accumulate = user.getAccumulate();

            Integer target = user.getTarget();

            // 当日达标
            if (DateUtil.formatDate(daydate).equals(DateUtil.today())) {
                // 同一天
                daynum++;
            } else {
                daydate = DateUtil.date();
                daynum = 1;
            }
            // 设定目标的情况下
            if (target != null && target > 0 && daynum == target) {
                // 当月达标
                if (DateUtil.format(monthdate, "yyyy-MM").equals(DateUtil.format(DateUtil.date(), "yyyy-MM"))) {
                    // 同一个月
                    accumulatemonth++;
                } else {
                    monthdate = DateUtil.date();
                    accumulatemonth = 1;
                }
                accumulate++;
            }

            newUser.setId(user.getId());
            newUser.setDaydate(daydate);
            newUser.setDaynum(daynum);
            newUser.setMonthdate(monthdate);
            newUser.setAccumulate(accumulate);
            newUser.setAccumulatemonth(accumulatemonth);

            User user2 = userDao.getUserByTel(user.getTel());
            MyContext.getHttpSession().setAttribute(userAttr, user2);

            userDao.updateUser(newUser);

        }

        return ResultFactory.success(tractate);
    }

    /**
     * 根据短文id，获取评论，按时间降序排序,分页展示
     *
     * @param tractateid
     * @return
     */
    public Result getCriticismsByTractateId(Long tractateid, Integer pageNo, Integer pageNum) {
        if (tractateid == null || pageNo < 1 || pageNum < 1) {
            return ResultFactory.notice("数据不合法");
        }

        PageHelper.startPage(pageNo, pageNum);
        List<Criticism> list = tractateDao.getCriticismsByTractateId(tractateid);
        PageInfo<Criticism> pageInfo = new PageInfo<>(list);
        return ResultFactory.success(pageInfo);
    }

    /**
     * 添加评论
     *
     * @param criticism
     * @return
     */
    @Transactional
    public Result saveCriticism(Criticism criticism) {
        // 数据校验
        if (criticism.getUserid() == null) {
            return ResultFactory.notice("用户id不合法");
        }
        if (criticism.getTractateid() == null) {
            return ResultFactory.notice("短文id不合法");
        }
        if (StringUtils.isEmpty(criticism.getContent())) {
            return ResultFactory.notice("评论内容为空");
        }

        int result = tractateDao.saveCriticism(criticism);

        if (result > 0) {
            return ResultFactory.success("添加成功");
        } else {
            return ResultFactory.failure("添加失败");
        }

    }

}
